/// <reference types="uni-app" />

import { NETWORK_CONFIG } from '@/config/network.js'

export interface RequestOptions extends UniApp.RequestOptions {
  url: string;
  data?: any;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  header?: Record<string, string>;
}

export function request<T = any>(options: RequestOptions): Promise<T> {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('accessToken');
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      ...(options.header || {}),
    };
    if (token) {
      headers['Access-Token'] = `Bearer ${token}`;
    }

    const finalUrl = options.url.startsWith('http')
      ? options.url
      : `${NETWORK_CONFIG.API_BASE_URL}${options.url}`

    uni.request({
      ...options,
      url: finalUrl,
      header: headers,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data as T);
        } else if (res.statusCode === 401) {
          uni.showToast({ title: '请重新登录', icon: 'none' });
          uni.redirectTo({ url: '/pages/auth/login/index' });
          reject(res);
        } else {
          uni.showToast({ title: (res.data as any)?.message || '请求失败', icon: 'none' });
          reject(res);
        }
      },
      fail: (err) => {
        uni.showToast({ title: '网络错误', icon: 'none' });
        reject(err);
      }
    });
  });
}

// 可选：定时刷新token（伪代码，需后端支持refreshToken接口）
let refreshTimer: number | null = null;
export function startTokenRefreshInterval() {
  if (refreshTimer) clearInterval(refreshTimer);
  refreshTimer = setInterval(async () => {
    const refreshToken = uni.getStorageSync('refreshToken');
    if (refreshToken) {
      try {
        await request({
          url: '/auth/refresh',
          method: 'POST',
          data: { refreshToken }
        });
      } catch (e) {
        uni.removeStorageSync('accessToken');
        uni.removeStorageSync('refreshToken');
        uni.redirectTo({ url: '/pages/auth/login/index' });
      }
    }
  }, 1000 * 60 * 10); // 10分钟刷新一次
}

export function stopTokenRefreshInterval() {
  if (refreshTimer) clearInterval(refreshTimer);
  refreshTimer = null;
} 